/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.messaging.basic;

import org.proteusframework.core.api.model.INamespace;
import org.proteusframework.core.base.Namespace;
import org.proteusframework.core.util.Assert;
import org.proteusframework.platformservice.grammar.IGrammarInspector;
import org.proteusframework.platformservice.grammar.IllegalExpressionException;
import org.proteusframework.platformservice.messaging.AbstractMessageSink;
import org.proteusframework.platformservice.messaging.IMessageBean;
import org.proteusframework.platformservice.messaging.IMessageSinkProducer;
import org.proteusframework.platformservice.messaging.IMessageSinkSubscriber;
import org.proteusframework.platformservice.persistence.api.messagebean.IMessageBeanDescriptor;

import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Logger;

final class BlockingQueueMessageSink<T extends IMessageBean> extends AbstractMessageSink<T>
{
    private static final Logger logger = Logger.getLogger(BlockingQueueMessageSink.class.getCanonicalName());

    private final BlockingQueue<T> queue;

    public BlockingQueueMessageSink(INamespace namespace, Class<T> messageBeanClass, Properties metadata, int maximumCapacity)
    {
        super(namespace, messageBeanClass, metadata);
        this.queue = new ArrayBlockingQueue<T>(maximumCapacity);
    }

    @Override
    protected IMessageSinkSubscriber<T> processCreateSubscriberRequest(Properties metadata) throws IllegalArgumentException
    {
        String id = UUID.randomUUID().toString();
        return new QueueSubscriber<T>(new Namespace(Namespace.toCanonical(DefaultMessageService.NS), id), metadata, this);
    }

    @Override
    public IMessageSinkProducer<T> createProducer(Properties metadata)
    {
        String id = UUID.randomUUID().toString();
        return new QueueProducer<T>(new Namespace(Namespace.toCanonical(DefaultMessageService.NS), id), metadata, this);
    }

    @Override
    protected IMessageSinkSubscriber<T> processCreateSubscriberRequest(Properties metadata, IMessageBeanDescriptor messageBeanDescriptor, String filter) throws IllegalArgumentException, IllegalExpressionException
    {
        String id = UUID.randomUUID().toString();

        Assert.parameterNotNull(messageBeanDescriptor, "Parameter 'messageBeanDescriptor' must not be null");
        Assert.parameterNotNull(filter, "Parameter 'filter' must not be null");

        IGrammarInspector inspector = createGrammarInspector(messageBeanDescriptor);
        inspector.inspect(filter);


        if (inspector.isValidExpression())
        {
            if (inspector.getParameterCount() > 0)
            {
                throw new IllegalExpressionException("Parameter substitution is not supported by this message sink implementation");
            }

            return new QueueSubscriber<T>(new Namespace(Namespace.toCanonical(DefaultMessageService.NS), id), metadata, this);

        } else
        {
            StringBuilder buf = new StringBuilder("\n\nExpression Errors: ");

            for(String err: inspector.errors())
            {
                buf.append(err).append("\n");
            }

            buf.append("\n\n");

            throw new IllegalExpressionException("Illegal filter expression" + buf.toString());
        }
    }

    public BlockingQueue<T> getQueue()
    {
        return queue;
    }
}
